package com.liaozibo.jekyll.ui;

import com.liaozibo.jekyll.ui.command.BaseCommand;
import com.liaozibo.jekyll.ui.command.CommandRegistry;
import com.liaozibo.jekyll.util.ConsoleUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
@Slf4j
public class ConsoleUI {

    @Autowired
    private CommandRegistry commandRegistry;

    /**
     * 根据命令行参数执行对应操作
     * */
    public void run(String[] args) {
        if (args.length < 2 || args.length > 2) {
            showUsage();
            return;
        }
        BaseCommand command = commandRegistry.getCommand(BaseCommand.getKey(args[0], args[1]));
        if (command == null) {
            showUsage();
            return;
        }
        try {
            command.execute(args);
        } catch (Throwable e) {
            log.error(e.getMessage());
        }
    }

    private void showUsage() {
        Collection<BaseCommand> commandList = commandRegistry.getCommandList();
        ConsoleUtils.stdout("参数有误，请使用以下参数：");
        for (BaseCommand command : commandList) {
            System.out.println(command.getSubject() + " " + command.getAction());
        }
    }
}
